import * as os from 'os'
import * as crypto from 'crypto'

export class PreciseTime {
    constructor(private time:number[]) {

    }

    /**
     * 获取纳秒差
     * @returns {number}
     */
    getNano() {
        let diff = process.hrtime(this.time);
        return diff[0] * 1e9 + diff[1];
    }

    /**
     * 获取微妙差
     */
    getMicro() {
        let diff = process.hrtime(this.time);
        return diff[0] * 1e6 + diff[1] / 1e3;
    }

    /**
     * 获取毫秒差
     */
    getMilli() {
        let diff = process.hrtime(this.time);
        return diff[0] * 1e3 + diff[1] / 1e6;
    }
}

export class sys {

    static instanof(left:Object, right:Function) {
        if (left == null || left.constructor == null || right == null)
            return false;

        return left.constructor.name === right.name && left.constructor.length === right.length;
    }


    static getLocalIp() {
        var interfaces = os.networkInterfaces();
        for (var devName in interfaces) {
            var iface = interfaces[devName];
            for (var i = 0; i < iface.length; i++) {
                var alias = iface[i];
                if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                    return alias.address;
                }
            }
        }
    }

    /**
     * 获取当前纳秒
     * @returns {PreciseTime}
     */
    static getPreciseTime() {
        return new PreciseTime(process.hrtime());
    }


    static md5(val:string):string {
        let hash = crypto.createHash('md5');
        hash.update(val);
        return hash.digest('hex');
    }

    static sha1(val:string):string {
        let hash = crypto.createHash('sha1');
        hash.update(val);
        return hash.digest('hex');
    }

    static sha256(val:string):string {
        let hash = crypto.createHash('sha256');
        hash.update(val);
        return hash.digest('hex');
    }
}